package com.masterclient.app.modules.pickgoods.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.eoner.baselibrary.utils.NavigationBarUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.masterclient.app.R;
import com.masterclient.app.modules.pickgoods.beans.PickGoodsBean;

import java.util.List;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * @auther hxm
 * @date 2020/9/20.
 */
public class PickGoodsListAdapter extends BaseQuickAdapter<PickGoodsBean.ItemBean, BaseViewHolder> {

    private View view = null;
    private Activity activity;
    private LinearLayout viewRoot;
    private boolean isShowed = false;
    private PickGoodsSelectListener listener;
    private List<PickGoodsBean.ItemBean> list;
    private int heightDifference;

    public PickGoodsListAdapter(Activity activity, LinearLayout viewRoot, List<PickGoodsBean.ItemBean> list, PickGoodsSelectListener listener) {
        super(R.layout.view_item_pick_goods);
        this.viewRoot = viewRoot;
        this.activity = activity;
        this.listener = listener;
        this.list = list;
    }

    @Override
    protected void convert(BaseViewHolder helper, PickGoodsBean.ItemBean item) {
        CheckBox checkBox = helper.getView(R.id.checkBox);
        ImageView ivGood = helper.getView(R.id.iv_good);
        TextView tvTitle = helper.getView(R.id.tv_title);
        TextView tvSku = helper.getView(R.id.tv_skus);
        TextView tvStockLess = helper.getView(R.id.tv_stock_less);
        EditText etNum = helper.getView(R.id.et_num);

        checkBox.setChecked(item.isChecked);
        checkBox.setOnClickListener(v -> {
            if (checkBox.isChecked()) {
                listener.onCheckItem(true, item.productId, etNum.getText().toString());
            } else {
                listener.onCheckItem(false, item.productId, etNum.getText().toString());
            }
        });
        tvTitle.setText(item.name);
        tvSku.setText(item.attributeText);
        tvStockLess.setText(String.format("保管库存数量 %s", item.custodyQty));
        etNum.setText(item.num);
        ViewTransformUtil.glideImageView(mContext, item.image, ivGood,
                new RoundedCornersTransformation(ScreenUtils.dp2px(7), 0),
                R.mipmap.defaults, ScreenUtils.dp2px(107), ScreenUtils.dp2px(107));

        etNum.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            Rect r = new Rect();
            //获取当前界面可视部分
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
            //获取屏幕的高度
            int screenHeight = activity.getWindow().getDecorView().getRootView().getHeight();
            //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
            heightDifference = screenHeight - r.bottom - NavigationBarUtil.getCurrentNavigationBarHeight(activity);
            showAViewOverKeyBoard(heightDifference, etNum);
        });

        etNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int position = helper.getLayoutPosition();
                if (!TextUtils.isEmpty(s.toString()) && !TextUtils.isEmpty(list.get(position).maxNum) &&
                        Integer.parseInt(s.toString()) > Integer.parseInt(list.get(position).maxNum)){
                    etNum.setText(list.get(position).maxNum);
                    etNum.setSelection((list.get(position).maxNum + "").length());
                    list.get(position).num = list.get(position).maxNum;
                }else {
                    list.get(position).num = s.toString();
                }
                if (checkBox.isChecked()) {
                    listener.onCheckItem(true, list.get(position).productId, list.get(position).num);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        ImageView ivReduce = helper.getView(R.id.iv_reduce);
        ImageView ivPlus = helper.getView(R.id.iv_plus);
        int buyGoodsNum = TextUtils.isEmpty(etNum.getText().toString())?1:Integer.parseInt(etNum.getText().toString());
        int maxGoodsNum = TextUtils.isEmpty(item.maxNum)?1:Integer.parseInt(item.maxNum);
        if (buyGoodsNum > 1) {
            ivReduce.setImageResource(R.mipmap.icon_pick_goods_reduce);
        } else {
            ivReduce.setImageResource(R.mipmap.icon_pick_goods_reduce_grey);
        }
        if (buyGoodsNum < maxGoodsNum) {
            ivPlus.setImageResource(R.mipmap.icon_pick_goods_plus);
        } else {
            ivPlus.setImageResource(R.mipmap.icon_pick_goods_plus_grey);
        }

        ivReduce.setOnClickListener(v -> {
            int buyNum = TextUtils.isEmpty(etNum.getText().toString())?1:Integer.parseInt(etNum.getText().toString());
            int maxNum = TextUtils.isEmpty(item.maxNum)?1:Integer.parseInt(item.maxNum);
            buyNum--;
            if (buyNum > 1) {
                etNum.setText(String.valueOf(buyNum));
                item.num = String.valueOf(buyNum);
                ivReduce.setImageResource(R.mipmap.icon_pick_goods_reduce);
            } else {
                if (buyNum == 0){
                    ToastUtil.showToast("提货数量不能再减少啦");
                }
                etNum.setText("1");
                item.num = "1";
                ivReduce.setImageResource(R.mipmap.icon_pick_goods_reduce_grey);
            }
            if (buyNum < maxNum) {
                ivPlus.setImageResource(R.mipmap.icon_pick_goods_plus);
            } else {
                ivPlus.setImageResource(R.mipmap.icon_pick_goods_plus_grey);
            }
            if (checkBox.isChecked()) {
                listener.onCheckItem(checkBox.isChecked(), item.productId, etNum.getText().toString());
            }
            etNum.setSelection(etNum.getText().toString().length());
        });
        ivPlus.setOnClickListener(v -> {
            int buyNum = TextUtils.isEmpty(etNum.getText().toString())?1:Integer.parseInt(etNum.getText().toString());
            int maxNum = TextUtils.isEmpty(item.maxNum)?1:Integer.parseInt(item.maxNum);
            buyNum++;
            if (buyNum < maxNum) {
                etNum.setText(String.valueOf(buyNum));
                item.num = String.valueOf(buyNum);
                ivPlus.setImageResource(R.mipmap.icon_pick_goods_plus);
            } else {
                if (buyNum > maxNum){
                    ToastUtil.showToast("提货数量超过保管库存数量");
                }
                etNum.setText(String.valueOf(maxNum));
                item.num = String.valueOf(maxNum);
                ivPlus.setImageResource(R.mipmap.icon_pick_goods_plus_grey);
            }
            if (buyNum > 1) {
                ivReduce.setImageResource(R.mipmap.icon_pick_goods_reduce);
            } else {
                ivReduce.setImageResource(R.mipmap.icon_pick_goods_reduce_grey);
            }
            if (checkBox.isChecked()) {
                listener.onCheckItem(checkBox.isChecked(), item.productId, etNum.getText().toString());
            }
            etNum.setSelection(etNum.getText().toString().length());
        });
    }

    private void hideSoftInput(EditText et) {
        InputMethodManager inputManager = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(et.getWindowToken(), 0);
    }

    private void showAViewOverKeyBoard(int heightDifference, EditText et) {
        if (heightDifference > 0 && !isShowed) {//显示
            if (view == null) {//第一次显示的时候创建  只创建一次
                view = View.inflate(activity, R.layout.item_keyboard, null);
                TextView tvConfirm = view.findViewById(R.id.tv_confirm);
                tvConfirm.setOnClickListener(v -> {
                    if (view != null) {
                        view.setVisibility(View.GONE);
                        isShowed = false;
                    }
                    hideSoftInput(et);
                });
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ScreenUtils.dp2px(47));
                params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                params.bottomMargin = heightDifference;
                viewRoot.addView(view, params);
                isShowed = true;
            }
            view.setVisibility(View.VISIBLE);
            viewRoot.setVisibility(View.VISIBLE);
        } else {//隐藏
            if (view != null) {
                view.setVisibility(View.GONE);
                viewRoot.setVisibility(View.GONE);
                isShowed = false;
            }
        }
    }

    public interface PickGoodsSelectListener {
        void onCheckItem(boolean isCheck, String productId, String num);
    }
}
